package org.hk.jdbc;

import org.hk.entity.Admin;
import org.hk.entity.Department;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ReflectJDBC {
    public static  Connection init()throws ClassNotFoundException, SQLException, IllegalAccessException{
        Class.forName("com.mysql.jdbc.Driver");        //1.运行客户端程序
        Connection connection = DriverManager.getConnection("jdbc:mysql://rm-uf602584bl2795b8kro.mysql.rds.aliyuncs.com:3306/smilegoods?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false&allowPublicKeyRetrieval=true&testOnborrow =false", "admin_01", "Q1w2e3r4");
        return connection;
    }
    //方法泛型 在返回值前面声明占位符
    public static <T> List<T> getList(Connection connection,Class clazz) throws SQLException, IllegalAccessException, InstantiationException {
        PreparedStatement prep = connection.prepareStatement("select * from " + clazz.getSimpleName());
        ResultSet rs = prep.executeQuery();//执行查询得到结果集 //4.执行
        List<T> ts = new ArrayList<T>();
        while(rs.next()){//如果结果集还有下一条循环就继续
            T t = (T)clazz.newInstance();//准备一个java对象，成员变量没有值
            for(Field fd:clazz.getDeclaredFields()){
                String fdName = fd.getName();//通过反射得到类的成员变量名（刚好对应数据库表的字段名）
                Object obj = rs.getObject(fdName);//通过字段名得到结果集中的值
                fd.setAccessible(true);
                fd.set(t, obj);//将得到值赋值给 新产生的admin对象
            }//System.out.println(department);
            ts.add(t);
        }
        ts.forEach(System.out::println);
        return ts;
    }
    public static void main(String[] args) throws ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {
        Connection connection = ReflectJDBC.init();
        ReflectJDBC.getList(connection,Admin.class);
    }
}
